<template>
  <div v-if="editOpen">
    <t-table :size="tableSize" :selected-row-keys="selectedRowKeys"
              @select-change="(val)=>{selectedRowKeys=val}" rowKey="id" :data="data"
              :columns="columns">
      <template #sort="{ rowIndex }">
        {{ rowIndex + 1 }}
      </template>
      <template #unitId="{ row }">
        <t-tree-select :status="row.unitNameStatus" @change="(val,content)=>{row.unitId=content.node.data.id;if(row.unitName!==''){row.unitNameStatus = 'default'}}" v-if="row.isInnerCompany==='1'" style="width:390px" clearable filterable
                       :treeProps="{keys: {value: 'label'}}" v-model="row.unitName" :data="deptMenuOptions"
                       placeholder="选择单位">
          <div slot="tips" v-if="row.unitNameStatus==='error'">不能为空</div>
          <div slot="tips" v-else>搜索不到请切换外部单位后手输</div>
          <template #label>
            <t-switch
              size="medium"
              v-model="row.isInnerCompany"
              :label="['内部', '外部']"
              :customValue="['1', '0']"
              @change="()=>{row.unitName='';row.unitId=null;row.unitNameStatus='default'}"
            ></t-switch>
          </template>
        </t-tree-select>
        <t-select
          v-else
          v-model="row.unitName"
          creatable
          filterable
          placeholder="请输入"
          :status="row.unitNameStatus"
          @change="(val,content)=>{row.unitId = content.option?.id;if(row.unitName!==''){row.unitNameStatus = 'default'}}"
          :loading="companyLoading"
          @search="remoteCompanyMethod"
          :options="companyOptions"
          @create="createCompanyOptions"
          style="width: 390px;display: inline-block"
        >
          <div slot="tips" v-if="row.unitNameStatus==='error'">不能为空</div>
          <div slot="tips" v-else>搜索不到请切换外部单位后手输</div>
          <template #label>
            <t-switch
              size="medium"
              v-model="row.isInnerCompany"
              :label="['内部', '外部']"
              :customValue="['1', '0']"
              @change="()=>{row.unitName='';row.unitId=null;row.unitNameStatus='default'}"
            ></t-switch>
          </template>
        </t-select>
      </template>
      <template #empty>
        <span>暂无数据 请点击新增按钮</span>
      </template>
    </t-table>
    <div style="margin-top: 10px" class="btn-group-inline">
      <t-button @click="addData">新增</t-button>
      <t-button @click="upData">上移</t-button>
      <t-button @click="downData">下移</t-button>
      <t-button @click="delData">删除</t-button>
    </div>
  </div>
  <div v-else>
    <t-table  rowKey="id" :data="data"
              :columns="columns2">
      <template #sort="{ rowIndex }">
        {{ rowIndex + 1 }}
      </template>
      <template #unitId="{ row }">
        {{row.unitName}}
      </template>
    </t-table>
  </div>
</template>

<script>
export default {
  name: "standard-company",
  props: {
    value: {
      type: Array,
      default:() => [],
    },
    editOpen: {
      type: Boolean,
      default: false
    },
    tableSize: {
      type: String,
      default: 'medium'
    }
  },
  data() {
    return {
      companyLoading: false,
      companyOptions: [],
      deptMenuOptions:[],
      selectedRowKeys: [],
      dialogOpen: false,
      header: '新增起草单位',
      visible: true,
      formData: {
        sort: null,
        unitId: '',
        isInnerCompany:'1',
        unitName:""
      },
      rules: {
        unitId: [
          {
            required: true,
            message: "不能为空",
          }
        ],
      },
      data: [],
      columns: [
        {
          colKey: 'row-select',
          type: 'single',
          title: "选择",
          width: 64
        },
        {
          colKey: 'sort',
          title: "序号",
          align: "center",
          width: 64
        },
        {
          colKey: 'unitId',
          title: "起草单位",
          align: "center",
        },
      ],
      columns2: [
        {
          colKey: 'sort',
          title: "序号",
          align: "center",
          width: 64
        },
        {
          colKey: 'unitId',
          title: "起草单位",
          align: "center",
        },
      ]
    }
  },
  watch: {
    data: {
      deep: true,
      immediate: true,
      handler(val) {
        const newData = this.data.map((val, index) => ({...val, sort: index + 1}))
        this.$emit("input", newData);
      }
    },
    value: {
      deep: true,
      immediate: true,
      handler(val) {
        // if (val.length > 0 && this.data.length <= 0) {
        //   this.data = val;
        // }
        if(val && val.length>0){
          let newArr = val.map(data=>{
            return {
              ...data,
              initType: 'init'
            }
          })
          // 防止无限循环，简单比较一下
          if (JSON.stringify(val) !== JSON.stringify(this.data)) {
            this.data = newArr
          }
        }
      }
    },
  },
  async created(){
    if(this.editOpen){
      await this.getDeptTreeSelect(this.$store.state.user.deptId)
    }
  },
  methods: {
    createCompanyOptions(value){
      this.companyOptions.push({
        label:`${value}`,
        // label:`1`,
        value
      });
    },
    remoteCompanyMethod(search){
      this.companyLoading = true;
      this.$api.system.dept.selectAllOutDeptList({deptName:search}).then(response => {
        this.companyOptions = response.data.map(val=> ({
          ...val,
          label:`${val.deptName}`,
          value:val.deptName,
        }))
        this.companyLoading = false;
      }).catch((e) => {
        this.companyLoading = false;
        this.$message.error(e.toString());
      });
    },
    getDeptTreeSelect(){
      return this.$api.system.dept.treeSelectAllIn().then(response=>{
        this.deptMenuOptions = response.data
      }).catch(e=>{
        this.$message.error(e.toString())
      })
    },
    checkData() {
      const isValidate = this.data.every((val, index) => {
        if ( val.unitName === "") {
          this.$set(this.data[index], 'unitNameStatus', 'error')
          this.$message.error(`起草单位：第${index + 1}条内容不能为空`);
          return false;
        }
        this.$set(this.data[index], 'unitNameStatus', 'default')
        return true;
      });
      return isValidate;
    },
    addData() {
      const newId = Number(new Date().getTime()) + Number(Math.random() * 10)
      this.data.push({
        id: newId,
        unitId: null,
        isInnerCompany: "1",
        unitName:""
      })
    },
    upData() {
      if (this.selectedRowKeys.length <= 0) {
        this.$message.warning("请选择一行");
        return;
      }
      if (this.data[0].id === this.selectedRowKeys[0]) {
        this.$message.warning("已是第一行");
      } else {
        const index = this.data.findIndex((val) => val.id === this.selectedRowKeys[0])
        this.moveInArray(this.data, index, index - 1)
      }
    },
    downData() {
      if (this.selectedRowKeys.length <= 0) {
        this.$message.warning("请选择一行");
        return;
      }
      if (this.data[this.data.length - 1].id === this.selectedRowKeys[0]) {
        this.$message.warning("已是最后一行");
      } else {
        const index = this.data.findIndex((val) => val.id === this.selectedRowKeys[0])
        this.moveInArray(this.data, index, index + 1)
      }
    },
    delData() {
      if (this.selectedRowKeys.length <= 0) {
        this.$message.warning("请选择一行");
        return;
      }
      const index = this.data.findIndex((val) => val.id === this.selectedRowKeys[0])
      this.data.splice(index, 1)
      this.selectedRowKeys = [];
    },
    moveInArray(arr, ffrom, to) {
      // 删除当前的位置
      const item = arr.splice(ffrom, 1);
      // 确保还剩有元素移动
      if (!item.length) {
        this.$message.warning(`There is no item in the array at index ${ffrom}`);
      }
      // 移动元素到指定位置
      arr.splice(to, 0, item[0]);
    },
  }
}
</script>

<style lang="less" scoped>
//.t-form__item {
//  margin-bottom: var(--td-comp-margin-xxl);
//  margin-right: 0px
//}
</style>
